package cn.lili.controller.partner;

import cn.hutool.core.date.DateUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.vo.ExtensionVO;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.SmsSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import cn.lili.modules.system.service.SettingService;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.vo.WalletDetailVO;
import cn.lili.modules.wallet.service.WalletDetailService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr20191230.models.RecognizeIdentityCardRequest;
import com.aliyun.ocr20191230.models.RecognizeIdentityCardResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * create by yudan on 2022/3/31
 */
@RestController
@Api(tags = "用户端,合伙人管理")
@RequestMapping("/buyer/partner")
@EnableScheduling
public class PartnerBuyerController {

	@Autowired
	private EextensionService eextensionService;

	/**
	 * 店铺
	 *
	 * @return
	 */
	@Autowired
	private StoreService storeService;

	/**
	 * 订单
	 */
	@Autowired
	private OrderService orderService;
	@Autowired
	private SettingService settingService;

	@Autowired
	private WalletDetailService walletDetailService;

	@ApiOperation(value = "根据推广码获取推广信息")
	@GetMapping
	public ResultMessage<IPage<ExtensionVO>> getByPage(String extension, String type, PageVO page) {
		ExtensionVO extensionVO = new ExtensionVO();
		extensionVO.setExtension(extension);
		extensionVO.setType(type);
		IPage<ExtensionVO> ExtensionVOPage = eextensionService.getExtensionPage(extensionVO, page);
		List<ExtensionVO> ExtensionVOList = ExtensionVOPage.getRecords();
		for (ExtensionVO e : ExtensionVOList) {
			e.setMobile(e.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
		}
		ExtensionVOPage.setRecords(ExtensionVOList);
		return ResultUtil.data(ExtensionVOPage);
	}

	@ApiOperation(value = "根据推广码获取推广信息")
	@RequestMapping("/code")
	public ResultMessage<IPage<ExtensionVO>> getByPageCode(String extension, String type, PageVO page) {
		ExtensionVO extensionVO = new ExtensionVO();
		extensionVO.setExtension(extension);
		extensionVO.setType(type);
		IPage<ExtensionVO> ExtensionVOPage = eextensionService.getByPageCode(extensionVO, page);
		/*
		 * List<ExtensionVO> ExtensionVOList = ExtensionVOPage.getRecords(); for
		 * (ExtensionVO e :ExtensionVOList) {
		 * e.setMobile(e.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2")); }
		 * ExtensionVOPage.setRecords(ExtensionVOList);
		 */
		return ResultUtil.data(ExtensionVOPage);
	}

	@RequestMapping(value = "/getList")
	@ApiOperation(value = "查询合伙人收益详情")
	public ResultMessage<IPage<WalletDetailVO>> getList(PageVO page, String time) {
		QueryWrapper<WalletDetailVO> queryWrapper = new QueryWrapper<>();
		queryWrapper.and(wrapper -> wrapper.eq("d.payer", UserContext.getCurrentUser().getId()).or().eq("d.payee",
				UserContext.getCurrentUser().getId()));
		queryWrapper.in("d.transaction_type", DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_FW_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_HY_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_TS_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_SY_REFUND.name());
		int count = 0;
		int index = 0;
		if (time == null || "".equals(time.trim())) {
			count = 0;
		}
		while ((index = time.indexOf("-", index)) != -1) {
			index = index + 1;
			count++;
		}
		// 年-月-日
		if (count == 0) {
			queryWrapper.eq("DATE_FORMAT(d.create_time,'%Y')", time);
		} else if (count == 1) {
			queryWrapper.eq("DATE_FORMAT(d.create_time,'%Y-%m')", time);
		} else if (count == 2) {
			queryWrapper.eq("DATE_FORMAT(d.create_time,'%Y-%m-%d')", time);
		}
		IPage<WalletDetailVO> list = walletDetailService.getIncomeList(page, queryWrapper);
		return ResultUtil.data(list);
	}

	@RequestMapping(value = "/getWallet")
	@ApiOperation(value = "查询合伙人总收益")
	public ResultMessage<Map<String, Object>> getCommission(String type, String month) {
		Map<String, Object> map = new HashMap<>();
		AuthUser authUser = UserContext.getCurrentUser();
		String memberId = authUser.getId();
		Double income = 0D;
		Double incomeDay = 0D;
		Double incomeAll = 0D;

		if (type.equals("month")) {
			String format = "";
			if (StringUtils.isNotEmpty(month) || month.equals("")) {
				format = DateUtil.format(new Date(), "yyyy-MM");
			} else {
				format = month;
			}
			// queryWrapper.apply("date_format(d.create_time, '%Y-%m') = {0}", format);
			// queryWrapper.groupBy("DATE_FORMAT(d.create_time, '%Y-%m')");
			income = walletDetailService.getCommissionMonth(memberId, format);
		} else if (type.equals("year")) {
			String format = DateUtil.format(new Date(), "yyyy");
			// queryWrapper.apply("date_format(d.create_time, '%Y') = {0}", format);
			// queryWrapper.apply("DATE_FORMAT(d.create_time, '%Y')");
			income = walletDetailService.getCommissionYear(memberId, format);
		}
		String format = DateUtil.format(new Date(), "yyyy-MM-dd");
		// queryWrapperDay.apply("date_format(d.create_time, '%Y-%m-%d') = {0}",
		// DateUtil.today());
		// queryWrapperDay.groupBy("DATE_FORMAT(d.create_time,'%Y-%M-%D')");
		incomeDay = walletDetailService.getCommissionDay(memberId, format);
		incomeAll = walletDetailService.getCommissionAll(memberId, null);
		map.put("income", income);
		map.put("incomeDay", incomeDay);
		map.put("incomeAll", incomeAll);
		return ResultUtil.data(map);
	}

	@RequestMapping(value = "/getYear")
	@ApiOperation(value = "查询合伙人年收益")
	public ResultMessage<IPage<WalletDetailVO>> getYear(PageVO page) {
		return ResultUtil.data(walletDetailService.findYear(page, UserContext.getCurrentUser().getId()));
	}

	@RequestMapping(value = "/getMonth")
	@ApiOperation(value = "查询合伙人月收益")
	public ResultMessage<IPage<WalletDetailVO>> getMonth(PageVO page) {
		QueryWrapper<WalletDetailVO> queryWrapper = new QueryWrapper();
		queryWrapper.eq("d.payee", UserContext.getCurrentUser().getId());
		queryWrapper.in("d.transaction_type", DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_FW_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_HY_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_TS_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_SY_REFUND.name());
		// 根据传进来的开始日期，查询所有该日期是数据，但是数据库中保存是时间，所以需要使用apply查询方式并格式化。
		String format = DateUtil.format(new Date(), "yyyy-MM");
		queryWrapper.apply("date_format(d.create_time, '%Y-%m') = {0}", format);
		return ResultUtil.data(walletDetailService.findMonth(page, null, null));
	}

	@RequestMapping(value = "/getDay")
	@ApiOperation(value = "查询合伙人日收益")
	public ResultMessage<IPage<WalletDetailVO>> getDay(PageVO page) {
		QueryWrapper<WalletDetailVO> queryWrapper = new QueryWrapper();
		queryWrapper.eq("d.payee", UserContext.getCurrentUser().getId());
		queryWrapper.in("d.transaction_type", DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_FW_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_HY_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_TS_REFUND.name(),
				DepositServiceTypeEnum.WALLET_COMMISSION_SY_REFUND.name());
		// 根据传进来的开始日期，查询所有该日期是数据，但是数据库中保存是时间，所以需要使用apply查询方式并格式化。
		queryWrapper.apply("date_format(d.create_time, '%Y-%m-%d') = {0}", DateUtil.today());

		return ResultUtil.data(walletDetailService.findDay(page, null, null));
	}

	@RequestMapping("/getCertificateIdentification")
	public ResultMessage getCertificateIdentification(String url) throws Exception {
		Setting setting = settingService.get(SettingEnum.SMS_SETTING.name());
		SmsSetting smsSetting = new Gson().fromJson(setting.getSettingValue(), SmsSetting.class);

		com.aliyun.ocr20191230.Client client = createClient(smsSetting.getAccessKeyId(), smsSetting.getAccessSecret());
		RecognizeIdentityCardRequest recognizeIdentityCardRequest = new RecognizeIdentityCardRequest().setImageURL(url)
				.setSide("face");
		RuntimeOptions runtime = new RuntimeOptions();
		try {
			// 复制代码运行请自行打印 API 的返回值
			RecognizeIdentityCardResponse response = client
					.recognizeIdentityCardWithOptions(recognizeIdentityCardRequest, runtime);
			String idNumber = response.body.getData().getFrontResult().getIDNumber();
			String res = JSON.toJSONString(response.body.getData().getFrontResult());
			JSONObject res_obj = JSON.parseObject(res);
			res_obj.put("num", idNumber);
			return ResultUtil.data(res_obj.toJSONString());
		} catch (TeaException error) {
			// 如有需要，请打印 error
			com.aliyun.teautil.Common.assertAsString(error.message);
		} catch (Exception _error) {
			TeaException error = new TeaException(_error.getMessage(), _error);
			// 如有需要，请打印 error
			com.aliyun.teautil.Common.assertAsString(error.message);
		}
		return ResultUtil.success(ResultCode.ERROR);
	}

	public static com.aliyun.ocr20191230.Client createClient(String accessKeyId, String accessKeySecret)
			throws Exception {
		Config config = new Config()
				// 您的 AccessKey ID
				.setAccessKeyId(accessKeyId)
				// 您的 AccessKey Secret
				.setAccessKeySecret(accessKeySecret);
		// 访问的域名
		config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
		return new com.aliyun.ocr20191230.Client(config);
	}

	// 查询未消费并且未充值的人数
	@RequestMapping("/unbind")
	public ResultMessage getUnbindCount(String extension) {
		List<Extension> list = eextensionService.getUnbindCount(extension);
		return ResultUtil.data(list.size());
	}

	// 查询未消费并且未充值的人数 解绑
	@Scheduled(cron = "0 0 0 1/1 * ?") // 每天凌晨执行
	public ResultMessage updateUnbind() {
		List<Extension> extensionList = eextensionService.updateUnbind(null);
		for (Extension extension : extensionList) {
			extension.setDeleteFlag(true);
			eextensionService.updateById(extension);
		}
		return ResultUtil.data(ResultCode.SUCCESS);
	}

	// 证书
	@RequestMapping("/certificate")
	public ResultMessage getCertificate() {
		return ResultUtil.data(eextensionService.getCertificate(UserContext.getCurrentUser().getId()));
	}

	@RequestMapping("/profit")
	public ResultMessage getMyProfit(PageVO page, String type, String month) {
		IPage<WalletDetailVO> profit = null;
		String memberId = UserContext.getCurrentUser().getId();
		if (StringUtils.isNotEmpty(type) && type.equals("day")) {
			// 根据传进来的开始日期，查询所有该日期是数据，但是数据库中保存是时间，所以需要使用apply查询方式并格式化。
			String format = DateUtil.format(new Date(), "yyyy-MM-dd");
			// queryWrapper.apply("date_format(d.create_time, '%Y-%m-%d') = {0}", format);
			profit = walletDetailService.findDay(page, memberId, format);
		} else if (StringUtils.isNotEmpty(type) && type.equals("month")) {
			String format = "";
			// 根据传进来的开始日期，查询所有该日期是数据，但是数据库中保存是时间，所以需要使用apply查询方式并格式化。
			if (StringUtils.isNotEmpty(month) || month.equals("")) {
				format = DateUtil.format(new Date(), "yyyy-MM");
			} else {
				format = month;
			}

			// queryWrapper.apply("date_format(d.create_time, '%Y-%m') = {0}", format);
			profit = walletDetailService.findMonth(page, memberId, format);
		} else if (StringUtils.isNotEmpty(type) && type.equals("year")) {
			profit = walletDetailService.findYear(page, memberId);
		}
		return ResultUtil.data(profit);
	}

}
